<script setup>
import {ArrowDown, Avatar, Bicycle, Location, OfficeBuilding, QuartzWatch, Setting} from "@element-plus/icons-vue";
import {nextTick, onMounted, provide, ref} from "vue";
import {confirmMessage, showMessage} from "../util/message.js";
import {doGet, doPost, doPut} from "../util/request.js";
import {TOKEN_NAME} from "../util/constants.js";
import {useRoute} from "vue-router";

// 页面渲染之后执行的内容
onMounted(()=>{
  // 查询当前登录用户信息
  loadLoginUserInfo()
  // 激活菜单
  computeActivePath()
})

// 获取路由参数对象
let route = useRoute()

// 计算激活菜单路径
const computeActivePath = () => {
  // 获取当前路由的路径 ,/dashboard/user , /dashboard/user/detail/9 ,/dashboard/user/detail/xx/xxx/9
  let templatePath = route.path
  // 将获取当前路由的路径通过“/”进行分隔，/dashboard/user -> ["",“dashboard”,“user”] , /dashboard/user/detail/9 -> ["","dashboard","user","detail","9"]
  let pathArr = templatePath.split("/")
  // 判断分隔后路径数组的长度
  if (pathArr.length > 3) {
    activePath.value = "/" + pathArr[1] + "/" + pathArr[2];
  } else {
    activePath.value = templatePath;
  }
}

// 创建登录用户信息响应式对象
const loginUserInfo = ref({})

// 查询当前登录用户信息函数
const loadLoginUserInfo = () => {
  // 发送get请求查询登录用户信息
  doGet('/api/user/info',{}).then(resp => {
    if (resp.data.code === 200) {
      loginUserInfo.value = resp.data.data
    } else {
      showMessage("查询登录用户信息失败，原因："+resp.data.msg,'error')
    }
  })
}

// 用户退出
const logout = () =>{
  confirmMessage('您真的要退出吗？')
      .then(() => {
        doPost('/api/logout',{}).then(resp => {
          if (resp.data.code === 200) {
            // 清除token
            sessionStorage.removeItem(TOKEN_NAME)
            localStorage.removeItem(TOKEN_NAME)
            // 跳转到登录页面
            window.location.href = '/'
          } else {
            showMessage("退出失败，原因：" + resp.data.msg,'error')
          }
        })
      })
}
// 我的资料弹出层显示控制变量
const userInfoDialogVisible = ref(false)
// 我的资料用户对象
const userDetailInfo = ref({})
// 显示我的资料对话框
const showUserInfo = () => {
  // 显示我的资料对话框
  userInfoDialogVisible.value = true
  // 发送请求，查询登录用户的详细信息
  doGet('/api/user/login/detail/info',{})
      .then(resp => {
        if (resp.data.code === 200) {
          userDetailInfo.value = resp.data.data;
        } else {
          showMessage('查询用户详细信息失败，原因：'+resp.data.msg,'error')
        }
      })
}

// 修改密码弹出层显示控制变量
const modifyPwdDialogVisible = ref(false)
// 修改密码表单对象
const modifyPwdForm = ref({})
// 判断确认密码输入是否一致
const checkConfirmPwd = (rule, value, callback) => {
  if (value != modifyPwdForm.value.newPwd) {
    callback(new Error('两次密码输入不一致.'))
  } else {
    callback()
  }
}
// 验证旧密码是否正确
const checkOldPwd = (rule, value, callback) => {
  // 发送请求验证旧密码是否正确
  doGet('/api/user/checkLoginPwd',{
    oldPwd:value
  })
  .then(resp => {
    if (resp.data.code == 200) {
      // 获取比较的结果
      if (!resp.data.data) {
        callback(new Error('原密码不正确'));
      } else {
        callback()
      }
    } else {
      callback()
    }
  })


}

// 修改密码表单元素校验规则
const modifyPwdRules = {
  oldPwd: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
    { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,10}$/, message: '密码由6-20位数字和字母组成', trigger: 'blur'},
    { validator: checkOldPwd, trigger: 'blur' }
  ],
  newPwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
    { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,10}$/, message: '密码由6-20位数字和字母组成', trigger: 'blur'}
  ],
  confirmPwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
    { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,10}$/, message: '密码由6-20位数字和字母组成', trigger: 'blur'},
    { validator: checkConfirmPwd, trigger: 'blur' }
  ]
}
const modifyRuleFormRef = ref()
// 提交修改密码表单
const submitModifyForm = (formEL) => {
  if (!formEL) return
  formEL.validate(valid => {
    if (valid) {
      // 修改登录密码请求
      doPut('/api/user/password',{
        loginPwd:modifyPwdForm.value.newPwd
      }).then(resp => {
        if (resp.data.code === 200) {
          showMessage('修改密码成功','success')
          // 清空token
          localStorage.removeItem(TOKEN_NAME)
          sessionStorage.removeItem(TOKEN_NAME)
          window.location.href = '/'
        } else {
          showMessage("修改密码失败，原因："+resp.data.msg,'error')
        }
      })
    }
  })
}

// 控制右侧内容体显示的状态
let isRouterAlive = ref(true)

const flushPage = () => {
  // 页面隐藏
  isRouterAlive.value = false
  nextTick(()=>{
    // 页面显示
    isRouterAlive.value = true
  })
}

provide('flushPage',flushPage)
provide('company','北京动力节点')

// 激活的路径
let activePath = ref('')
</script>

<template>
  <el-container>
    <!-- 左侧（菜单） -->
    <el-aside width="200px">
      <div class="menu-header">动力云客管理系统</div>

      <el-menu
          active-text-color="#ffd04b"
          background-color="#545c64"
          class="el-menu-vertical-demo"
          :default-active="activePath"
          text-color="#fff"
          :router="true"
          style="border-right: 0px solid var(--el-menu-border-color);"
          @open="handleOpen"
          @close="handleClose"
      >
        <el-sub-menu :index="index" v-for="(menu,index) in loginUserInfo.menuList">
          <template #title>
            <el-icon><component :is="menu.icon"/></el-icon>
            <span>{{ menu.name }}</span>
          </template>
          <el-menu-item :index="childMenu.url" v-for="childMenu in menu.chileMenuPermissionList">
            <template #title>
              <el-icon><component :is="childMenu.icon"/></el-icon>
              <span>{{ childMenu.name }}</span>
            </template>
          </el-menu-item>
        </el-sub-menu>

      </el-menu>
    </el-aside>

    <!-- 右侧 -->
    <el-container>

      <!-- 右侧：头部 -->
      <el-header>
        <el-dropdown>
            <span class="el-dropdown-link">
              {{ loginUserInfo.name }}
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="showUserInfo">我的资料</el-dropdown-item>
                <el-dropdown-item @click="modifyPwdDialogVisible = true">修改密码</el-dropdown-item>
                <el-dropdown-item @click="logout">用户退出</el-dropdown-item>
              </el-dropdown-menu>
            </template>
        </el-dropdown>
      </el-header>
      <!-- 右侧：内容部分 -->
      <el-main>
        <!-- 标签会根据请求路由地址所对应的页面将其渲染在此 -->
        <router-view v-if="isRouterAlive"/>
      </el-main>

      <!-- 右侧：尾部 -->
      <el-footer>
        @版本所有 2009-2099 北京动力节点教育科技有限公司
      </el-footer>
    </el-container>
  </el-container>

  <!--  我的资料弹出层-->
  <el-dialog
      v-model="userInfoDialogVisible"
      title="我的资料"
      width="500"
      :close-on-click-modal=false
      :show-close=false
      align-center>

    <el-form
        style="max-width: 600px"
        :model="userDetailInfo"
        status-icon
        label-width="auto"
    >
      <el-form-item label="用户编号：" >
        {{userDetailInfo.id}}
      </el-form-item>
      <el-form-item label="登录账号：" >
        {{userDetailInfo.loginAct}}
      </el-form-item>
      <el-form-item label="用户姓名：" >
        {{userDetailInfo.name}}
      </el-form-item>
      <el-form-item label="用户手机：" >
        {{userDetailInfo.phone}}
      </el-form-item>
      <el-form-item label="用户邮箱：" >
        {{userDetailInfo.email}}
      </el-form-item>
      <el-form-item label="账户是否过期：" >
        {{userDetailInfo.accountNoExpired == 1?'否':'是'}}
      </el-form-item>
      <el-form-item label="密码是否过期：" >
        {{userDetailInfo.credentialsNoExpired == 1?'否':'是'}}
      </el-form-item>
      <el-form-item label="账户是否锁定：" >
        {{userDetailInfo.accountNoLocked == 1?'否':'是'}}
      </el-form-item>
      <el-form-item label="账户是否启用：" >
        {{userDetailInfo.accountEnabled == 1?'否':'是'}}
      </el-form-item>
      <el-form-item label="创建时间：" >
        {{userDetailInfo.createTime}}
      </el-form-item>
      <el-form-item label="创建人：" >
        {{userDetailInfo.createByName}}
      </el-form-item>
      <el-form-item label="编辑时间：" >
        {{userDetailInfo.editTime}}
      </el-form-item>
      <el-form-item label="编辑人：" >
        {{userDetailInfo.editByName}}
      </el-form-item>
      <el-form-item label="最近登录时间：" >
        {{userDetailInfo.lastLoginTime}}
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="userInfoDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="userInfoDialogVisible = false">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <!--  修改密码弹出层-->
  <el-dialog
      v-model="modifyPwdDialogVisible"
      title="修改密码"
      width="500"
      :close-on-click-modal=false
      :show-close=false
      align-center>

    <el-form
        ref="modifyRuleFormRef"
        style="max-width: 600px"
        :model="modifyPwdForm"
        :rules="modifyPwdRules"
        status-icon
        label-width="auto"
    >
      <el-form-item label="原密码" prop="oldPwd">
        <el-input type="password" v-model="modifyPwdForm.oldPwd" autocomplete="off" />
      </el-form-item>
      <el-form-item label="新密码" prop="newPwd">
        <el-input type="password" v-model="modifyPwdForm.newPwd" autocomplete="off" />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPwd">
        <el-input type="password" v-model="modifyPwdForm.confirmPwd" autocomplete="off" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="modifyPwdDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitModifyForm(modifyRuleFormRef)">确认</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<style scoped>
.el-aside{
  background-color: #888888;
  height: calc(100vh);
  text-align: center;
}
.menu-header{
  color: aliceblue;
  text-align: center;
  font-size: large;
  font-weight: bolder;
  line-height: 50px;
}
.el-header{
  background-color: #888888;
  height: 51px;
  text-align: center;
  line-height:45px;
}
.el-dropdown{
  float: right;
  font-weight: bolder;
  font-size: 15px;
  margin-top: 15px;
  cursor: pointer;
}
.el-dropdown-link{
  color: ghostwhite;
}
.el-footer{
  text-align: center;
  font-size: 12px;
  color: black;
  line-height: 45px;
}
.el-container{
  height: calc(100vh);
}
</style>